let logger = require('../../utils/logger')
let app = getApp()
Page({
  data: {},
  onLoad: function () {
  },
  onShow: function () {
    console.log(app.globalData)
    console.log(app)
  },
  onClick () {
    var that = this
    wx.login({
      success (loginRes) {
        var code = loginRes.code
        
        wx.getUserInfo({
          success: function (res) {
            app.globalData.userInfo = res.userInfo
            
            let data = {
              code: code,
              rawData: res.rawData,
              signature: res.signature,
              encryptedData: res.encryptedData,
              iv: res.iv
            }
            that.httpLogin(data)
          },
          fail (res) {
            console.log('fail', res)
            wx.openSetting({
              success: function (data) {
                if (data) {
                  if (data.authSetting['scope.userInfo'] == true) {
                    logger.info('设置权限成功')
                  }
                }
              }
            })
          }
        })
      }
    })
  },
  httpLogin (data) {
    app.http.post({
      path: '/wx/login',
      data: data,
      success (response) {
        logger.debug('三方服务器登录成功', response)
        
        let data = response
        var token = data.token
        var userId = data.id
        wx.setStorageSync('token', token)
        wx.setStorageSync('userId', userId)
        
        that.globalData.token = token
        that.globalData.userId = userId
  
        wx.navigateBack({
          delta: 1
        })
      }
    })
  }
})